// 封装购物车模块
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import { useUserStore } from "./user"
import { insertCartAPI, findNewCartListAPI, delCartAPI } from "@/apis/cart"

export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)


    // 1.定义state - cartList
    const cartList = ref([]);

    // 2. 定义action - addCart
    const addCart = async (goods) => {
        // 添加购物车操作
        const { skuId, count } = goods;

        if (isLogin.value) {
            // 登录之后的加入购物车逻辑
            await insertCartAPI({ skuId, count });

            updateNewList();

        } else {
            // 已添加过, count + 1
            // 没有添加过直接push
            // 思路: 判断匹配传递过来的商品对象中的skuId能不能在cartList中找到
            const item = cartList.value.find(item => goods.skuId === item.skuId);
            if (item) {
                // 找到了
                item.count++
            } else {
                cartList.value.push(goods);
            }
        }


    }

    // 删除购物车中商品
    const delCart = async (skuId) => {
        if (isLogin.value) {
            // 调用接口实现购物车中删除功能
            await delCartAPI([skuId])
            updateNewList()

        } else {
            // 找到要删除的下标值
            const idx = cartList.value.findIndex((item) => skuId === item.skuId);
            cartList.value.splice(idx, 1);
        }
    }

    // 清除购物车
    const clearCart = () => {
        cartList.value = []
    }

    // 获取最新购物车列表
    const updateNewList = async () => {
        // 获取最新的购物车列表
        const res = await findNewCartListAPI();
        // 覆盖本地的购物车列表
        cartList.value = res.result;
    }

    /**
     * @name 计算属性
     * 1. 总的数量 所有项的count之和
     * 2. 总价 所有项的count * price之和
     */
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))

    // 单选
    const singleClick = (skuId, selected) => {
        const item = cartList.value.find((item) => item.skuId === skuId);
        item.selected = selected;
    }

    // 是否全选
    const isAll = computed(() => cartList.value.every(item => item.selected));

    // 全选
    const allCheck = (selected) => {
        // 把cartList中每一项的selected都修改为当前的全选框状态
        cartList.value.forEach(item => item.selected = selected);
    }

    // 已选择数量
    const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0));

    return {
        cartList,
        addCart,
        delCart,
        allCount,
        allPrice,
        singleClick,
        isAll,
        allCheck,
        selectedCount,
        clearCart,
        updateNewList
    }
}, {
    persist: true
})